<div>
  <div>
    <a-typography-title :level="3">新增一部电视剧</a-typography-title>
    <a-divider></a-divider>
  </div>
  <div>
    <div v-show="current==0">
      <div class="w-9/12 mb-3">
        <div class="mb-3">
          <a-typography-title :level="4">从豆瓣搜索</a-typography-title>
        </div>
        <div>
          <div class="mb-3">
            <a-input-search v-model:value="searchDoubanValue" placeholder="请输入电视剧名称" enter-button
              :loading="searchLoading" @search="searchDoubanHandle" />
          </div>
          <div class="mb-3" v-if="doubanList.length > 0">
            <div v-for="(item, idx) in doubanList" key="idx" class="douban_li_item" >
              <div class="flex ">
                <div>
                  <a-image :src="item.pic" width="65px" height="97px" />
                </div>
                <div style="flex: 1;margin-left: 16px;">
                  <div style="font-size: 20px;font-weight: 600;">{{item.name}}</div>
                  <div><a-rate disabled :value="item.score_2" allow-half></a-rate><span>{{item.score}}</span></div>
                  <div style="font-size: 12px;color: #999;">{{item.abstract}}</div>
                  <div style="font-size: 12px;color: #999;"> {{item.abstract2}}</div>
                </div>
                <div style="width: 100px;" class="flex items-center justify-center">

                  <div v-if="doubanSelect == item.href">
                    <a-tooltip>
                      <template #title>再次点击取消选择</template>
                      <div style="cursor: pointer;" class="flex items-center" @click="cacelJoinPlayDb">
                        <svg class="icon" aria-hidden="true" style="color: green">
                          <use xlink:href="#icon-duihao"></use>
                        </svg>
                        <span class="text-black ml-2">已选择</span>
                      </div>
                    </a-tooltip>
                  </div>

                  <div v-else>
                    <div class="spin_loading" v-if="item.loading">
                      <svg focusable="false" data-icon="loading" width="1em" height="1em" fill="#00b96b"
                        aria-hidden="true" viewBox="0 0 1024 1024">
                        <path
                          d="M988 548c-19.9 0-36-16.1-36-36 0-59.4-11.6-117-34.6-171.3a440.45 440.45 0 00-94.3-139.9 437.71 437.71 0 00-139.9-94.3C629 83.6 571.4 72 512 72c-19.9 0-36-16.1-36-36s16.1-36 36-36c69.1 0 136.2 13.5 199.3 40.3C772.3 66 827 103 874 150c47 47 83.9 101.8 109.7 162.7 26.7 63.1 40.2 130.2 40.2 199.3.1 19.9-16 36-35.9 36z">
                        </path>
                      </svg>
                    </div>
                    <span v-else @click="selectDoubanItem(item)" class="span_link">选择添加</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-show="current==1">
      <div>
        <div class="w-9/12 flex flex-row">
          <a-form-item label="电视剧封面">

            <a-upload v-if="dataType=='input'" :max-count="1" ref="imageUploadRef" name="avatar"
              list-type="picture-card" class="avatar-uploader" :before-upload="getFileHandle"
              @remove="imageRemoveFileHandle" accept="image/*">
              <div>
                <div class="ant-upload-text">上传封面</div>
              </div>
            </a-upload>
            <div v-else>
              <a-image :src="tvData.pic" width="135px" height="202px"></a-image>
            </div>
          </a-form-item>
        </div>
        {{nameErrors}}
        <div class="w-9/12 flex flex-row">
          <div class="w-6/12">
            <a-form-item label="电视剧名称" class="w-11/12" :validate-status="v$.name.$error?'error':'success'"
              :help="errors.name">
              <a-input placeholder="请输入电视剧名称" v-model:value="tvData.name" @blur="v$.name.$touch" />
            </a-form-item>
          </div>
          <div class="w-6/12">
            <a-form-item label="电视剧分类" class="w-11/12" :validate-status="v$.classify.$error?'error':'success'"
              :help="errors.classify">
              <a-select placeholder="请输入电视剧分类" v-model:value="tvData.classify" :options="classifyList"
                @blur="v$.classify.$touch" mode="multiple">
              </a-select>
            </a-form-item>
          </div>
        </div>
        <div class="w-9/12 flex flex-row">
          <div class="w-6/12">
            <a-form-item label="电视剧演员" class="w-11/12" :validate-status="v$.actors.$error?'error':'success'"
              :help="errors.actors">
              <a-input placeholder="请输入电视剧演员" v-model:value="tvData.actors" @blur="v$.actors.$touch" />
            </a-form-item>
          </div>
          <div class="w-6/12">
            <a-form-item label="电视剧评分" class="w-11/12" :validate-status="v$.score.$error?'error':'success'"
              :help="errors.score">
              <a-input placeholder="请输入电视剧评分" v-model:value="tvData.score" @blur="v$.score.$touch" />
            </a-form-item>
          </div>
        </div>
        <div class="w-9/12 flex flex-row">
          <div class="w-6/12">
            <a-form-item label="电视剧标识" class="w-11/12">
              <div class="flex flex-row">
                <a-input v-model:value="tvData.word" :disabled="true" placeholder="根据电视剧名称自动生成">
                  <template #addonAfter>
                    <div style="cursor: pointer">
                      <CopyOutlined />
                    </div>
                  </template>
                </a-input>
              </div>
            </a-form-item>
          </div>
          <div class="w-6/12">
            <a-form-item label="是否显示  " class="w-11/12">
              <a-switch v-model:checked="tvData.show" checked-children="显示" un-checked-children="隐藏" />
            </a-form-item>
          </div>
        </div>
        <div class="w-9/12 flex flex-row">
          <a-form-item label="电视剧详情" class="w-full" :validate-status="v$.desc.$error?'error':'success'"
            :help="errors.desc">
            <a-textarea :rows="6" placeholder="请输入电视剧描述信息" v-model:value="tvData.desc" @blur="v$.desc.$touch" />
          </a-form-item>
        </div>
      </div>
    </div>
    <div v-show="current==2">
      <div class="mb-4">
        <div class="mb-4">选择电视剧存储格式</div>
        <div>
          <a-radio-group v-model:value="saveType">
            <a-radio value="mp4">mp4</a-radio>
          </a-radio-group>
        </div>
      </div>
      <div>
        <div class="mb-4">选择电视剧剧集存放位置</div>
        <a-input-group compact>
          <a-input v-model:value="folderPath" :disabled="true" style="width: 40vw; color: black;"></a-input>
          <a-button type="primary" @click="getFolderPath">选择文件夹</a-button>
        </a-input-group>
        <div>
        </div>
      </div>
    </div>
    <div v-show="current==3">
      <a-result :status="resultData.code==200 ? 'success' : 'error'"
        :title="resultData.code==200 ? '添加电视剧成功' : '添加电视剧失败'"
        :sub-title="resultData.code==200 ? '您可以选择继续添加，或者前往修改已添加内容' : resultData.msg">
        <template #extra>
          <a-button v-if="resultData.code!=200" @click="changeCurrent(2)">上一步</a-button>
          <a-button type="primary" @click="reloadHandle">
            {{ resultData.code==200 ? '继续添加' : '重新添加' }}
          </a-button>
          <a-button @click="goto('/admin/tv/list?menu_open=tv')">已添加列表</a-button>
        </template>
      </a-result>
    </div>
  </div>
</div>
<div style="width: 80%;" class="mt-10">
  <a-steps :current="current">
    <a-step title="获取数据" description="从豆瓣获取数据">
    </a-step>
    <a-step title="电视剧基本信息" description="填写电视剧基本信息">
    </a-step>
    <a-step title="电视剧剧集" description="选择电视剧所在文件夹">
    </a-step>
    <a-step title="添加完成" description="查看添加结果">
    </a-step>
  </a-steps>
</div>
<div style="margin-top: 30px;">
  <div v-if="current == 0">
    <a-button @click="nextHandleStep1" class="ml-2" type="primary">下一步</a-button>
    <a-button @click="changeCurrent(1)" class="ml-2">手动添加</a-button>
  </div>
  <div v-if="current == 1">
    <a-button @click="nextHandleStep2" class="ml-2" type="primary">下一步</a-button>
    <a-button @click="changeCurrent(0)" class="ml-2">上一步</a-button>
  </div>
  <div v-if="current == 2">
    <a-button @click="addTv" class="ml-2" type="primary">开始添加</a-button>
    <a-button @click="changeCurrent(1)" class="ml-2">上一步</a-button>
  </div>
</div>
<div v-if="current == 2">
  <a-divider></a-divider>
  <a-space direction="vertical">
    <a-typography-text type="secondary">说明</a-typography-text>
    <a-typography-text type="secondary">保存为m3u8格式需要安装配置好 <a-typography-text code>ffmpeg</a-typography-text>
      并在服务端配置文件处填写好软件地址，才能使用
    </a-typography-text>
  </a-space>
</div>
</div>
<script>

  function useValidate(tvData) {
    const { required, maxLength, helpers } = VuelidateValidators;
    const rules = computed(() => {
      return {
        name: {
          required: helpers.withMessage('电视剧名称是必填项！', required)
        },
        classify: {
          required: helpers.withMessage('请选择电视剧分类！', required)
        },
        actors: {
          required: helpers.withMessage('电视剧演员是必填项！', required)
        },
        score: {
          required: helpers.withMessage('电视剧评分是必填项！', required),
          maxLength: helpers.withMessage('电视剧评分不能超过5！', maxLength(5)),
        },
        desc: {
          required: helpers.withMessage('电视剧描述是必填项！', required)
        }
      };
    });
    const v$ = Vuelidate.useVuelidate(rules, tvData);
    const errors = ref({});
    for (let item in rules.value) {
      errors.value[item] = computed(() => {
        let errors = [];
        v$.value[item].$errors.forEach(e => {
          errors.push(e.$message);
        });
        return errors;
      });
    }
    return {
      v$,
      errors
    };
  }

  function useFile() {
    const fileData = ref(null);
    const imageRemoveFileHandle = () => {
      fileData.value = null;
    };

    const getFileHandle = (file) => {
      if (file.type.indexOf('image') == -1) {
        message.warn('您上传的封面图片格式不正确');
        imageUploadRef.value.files = [];
        return false;
      }
      fileData.value = file;
      console.log(file);
      return false;
    };
    return {
      fileData,
      imageRemoveFileHandle,
      getFileHandle
    };
  }

  function useTvSet() {
    let isFolderSelect = false;
    const folderPath = ref('');
    const saveType = ref('mp4');
    const setList = ref([]);
    socket.on('folder', data => {

      if (data.code != undefined && data.code == 200) {
        folderPath.value = data.path;
        setList.value = data.files.map((a, idx) => ({ id: idx, idx, file: a }));
        isFolderSelect = false;
        return;
      }
      Hint.warn(data.msg);
      isFolderSelect = false;
    });
    const getFolderPath = () => {
      if (isFolderSelect) {
        Hint.warn('正在选择文件夹中...');
        return;
      }
      isFolderSelect = true;
      socket.emit('file', { type: 'folder' });
    };
    return {
      folderPath,
      saveType,
      setList,
      getFolderPath,
    };
  }

  function useMain() {
    const current = ref(0);
    const dataType = ref('input');
    const searchValue = ref('');
    const searchDoubanValue = ref('');
    const doubanList = ref([]);
    const doubanSelect = ref(null);
    const searchLoading = ref(false)
    const classifyList = ref([]);
    const resultData = ref({ code: 400 });
    const tvData = reactive({
      name: '',
      score: '',
      desc: '',
      actors: '',
      classify: [],
      word: '',
      show: true,
      pic: ''
    });
    const Validate = useValidate(tvData);
    const TvSet = useTvSet();
    const FileHandle = useFile();
    const changeCurrent = (val) => {
      current.value = val;
    }
    const searchDoubanHandle = async () => {
      if (searchLoading.value) {
        Hint.error('正在搜索中...');
        return;
      }
      if (searchDoubanValue.value.length < 1) {
        Hint.error('请输入需要搜索的电视剧名称');
        return;
      }
      searchLoading.value = true;
      try {
        let ret = await axios.post('/v1/web/douban/search', {
          value: searchDoubanValue.value
        });
        if(ret.data.code!=200){
          Hint.warn(ret.data.msg);
          return;
        }
        doubanList.value = ret.data.data;
        searchLoading.value = false;
      } catch (e) {
        let msg = `获取数据失败`;
        searchLoading.value = false;
        Hint.error(msg);
        console.log(msg, e);
      }
    };
    const selectDoubanItem = async (params) => {
      try {
        params.loading = true;
        let ret = await axios.post("/v1/web/douban/item", { href: params.href });
        let dat = ret.data.data;
        tvData.name = dat.name
        tvData.score = dat.score
        tvData.desc = dat.desc
        tvData.actors = dat.actors
        tvData.classify = dat.classify.split("/")
        tvData.pic = dat.pic
        Hint.success('选择电视剧预设数据成功');
        dataType.value = "douban"
        doubanSelect.value = params.href;
        params.loading = false;
        changeCurrent(1);

      } catch (e) {
        params.loading = false;
        let msg = `获取数据失败`;
        Hint.error(msg);
        console.log(msg, e);
      }

    };
    const cancelSelectDoubanItem = () => {
      doubanSelect.value = null;
      presetData.value = {};
      Hint.success('已取消添加');
    };

    const getClassify = async () => {
      try {
        let ret = await await axios.post('/v1/web/tv/classify', { show: 'show' });
        let dat = ret.data.data;
        classifyList.value = dat.map(a => ({
          label: a.name,
          value: a.name
        }));
      } catch (e) {
        let msg = `获取电视剧分类失败`;
        Hint.error(msg);
        console.log(msg, e);
      }
    };
    const disposeBody = () => {
      let body = {};
      body.tv_data = _.clone(tvData);
      body.tv_data.classify = tvData.classify.join('/');
      body.folder_path = TvSet.folderPath.value;
      body.save_type = TvSet.saveType.value;
      body.data_type = dataType.value;
      return body;
    };
    const addTv = async () => {
      if (TvSet.folderPath.value.length < 1) {
        Hint.error('电视剧存储位置不能为空');
        return;
      }
      try {
        let body = disposeBody();
        let ret = await axios.post('/v1/web/tv/add', body);
        let dat = ret.data;
        changeCurrent(3)
        resultData.value = dat?.code == undefined ? { code: 400 } : dat;
        if (dat.code != 200) {
          console.log('添加电视剧失败');
          console.log(dat);
          return;
        }
        if (dataType.value != 'input') return;
        let fm = new FormData();
        fm.append('file', FileHandle.fileData.value);
        let upRet = await axios.post('/v1/upload/pic?' + Qs.stringify({
          word: body.tv_data.word,
          id: 1,
          type: 'tv'
        }), fm, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        console.log(upRet);
      } catch (e) {
        let msg = `添加电视剧失败`;
        Hint.error(msg);
        console.log(msg, e);
      }

    };


    const nextHandleStep1 = () => {
      if (doubanSelect.value == null) {
        Hint.warn('请搜索并选择要添加的预设数据');
        return;
      }
      changeCurrent(1)
    }
    const nextHandleStep2 = async () => {
      let validResult = await Validate.v$.value.$validate();
      if (dataType.value == 'input' && FileHandle.fileData.value == null) {
        Hint.warn('请上传电视剧封面');
        return;
      }
      if (!validResult) {
        Hint.warn('请正确填写表单信息');
        return;
      }
      if (dataType.value == 'input') {
        tvData.pic = FileHandle.fileData.value.name;
      }

      tvData.word = md5(tvData.name)
        .substring(8, 24);
      changeCurrent(2)
    }
    const prevHandle = () => {
      current.value--;
    };
    const reloadHandle = () => {
      location.reload();
    };
    onMounted(async () => {
      await getClassify();
      // Sortable({el: ''})
    });
    return {
      current,
      dataType,
      searchValue,
      classifyList,
      tvData,
      resultData,
      searchDoubanValue,
      doubanList,
      doubanSelect,
      searchLoading,
      changeCurrent,
      addTv,
      prevHandle,
      reloadHandle,
      searchDoubanHandle,
      selectDoubanItem,
      cancelSelectDoubanItem,
      nextHandleStep1,
      nextHandleStep2,
      ...Validate,
      ...FileHandle,
      ...TvSet,
    };
  }
</script>
